package cn.stronglink.asset.module.assetmanage.itasset.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.message.mq.topic.ReaderInfoSender;
import cn.stronglink.asset.message.mq.topic.entity.CollectBaseReceiverData;
import cn.stronglink.asset.message.mq.topic.entity.OnLightParam;
import cn.stronglink.asset.model.AssetExtMaintenance;
import cn.stronglink.asset.model.AssetExtUsing;
import cn.stronglink.asset.model.AssetRecord;
import cn.stronglink.asset.model.AssetTypeAttr;
import cn.stronglink.asset.model.AssetTypeValue;
import cn.stronglink.asset.model.Department;
import cn.stronglink.asset.model.ItAsset;
import cn.stronglink.asset.model.ItAssetExtPosition;
import cn.stronglink.asset.model.LightU;
import cn.stronglink.asset.model.Preset;
import cn.stronglink.asset.model.PresetDetail;
import cn.stronglink.asset.model.RfidState;
import cn.stronglink.asset.model.TRoom;
import cn.stronglink.asset.model.User;
import cn.stronglink.asset.module.alarm.mapper.AlarmMapper;
import cn.stronglink.asset.module.assetRecord.mapper.AssetRecordMapper;
import cn.stronglink.asset.module.assetmanage.attrvalue.mapper.AttrValueMapper;
import cn.stronglink.asset.module.assetmanage.instock.mapper.AssetExtMaintenanceMapper;
import cn.stronglink.asset.module.assetmanage.instock.mapper.PresetDetailMapper;
import cn.stronglink.asset.module.assetmanage.instock.mapper.PresetMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetExtPositionMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetMapper;
import cn.stronglink.asset.module.assetmanage.itasset.param.AssetExtPositionParam;
import cn.stronglink.asset.module.assetmanage.itasset.vo.AssetExlVo;
import cn.stronglink.asset.module.assetmanage.itasset.vo.ItAssetVo;
import cn.stronglink.asset.module.assetmanage.itasset.vo.LightAssetVo;
import cn.stronglink.asset.module.assetmanage.using.mapper.AssetExtUsingMapper;
import cn.stronglink.asset.module.basicdata.tRoom.mapper.TRoomMapper;
import cn.stronglink.asset.module.basicdata.tRoom.vo.RoomTreeNodeVo;
import cn.stronglink.asset.module.lightData.mapper.LightDataMapper;
import cn.stronglink.asset.module.readerInfo.mapper.ReaderInfoMapper;
import cn.stronglink.asset.module.rfidState.mapper.RfidStateMapper;
import cn.stronglink.suite.core.exception.BusinessException;
import cn.stronglink.suite.core.util.ContextUtils;
import cn.stronglink.suite.core.util.WebUtil;

@Service
@Transactional(rollbackFor=Exception.class) 
public class ItassetService {
	
	@Autowired
	private AlarmMapper alarmMapper;
	@Autowired
	private ItassetMapper itassetMapper;
	@Autowired
	private PresetDetailMapper presetDetailMapper;
	@Autowired
	private PresetMapper presetMapper;
	@Autowired
	private ItassetExtPositionMapper itassetExtPositionMapper;
	@Autowired
	private AssetExtUsingMapper usingMapper;	
	@Autowired
	private AssetExtMaintenanceMapper maintenanceMapper;
	@Autowired
	private TRoomMapper tRoomMapper;
	@Autowired
	private RfidStateMapper rfidStateMapper;
	@Autowired
	private ReaderInfoMapper readerInfoMapper;
	@Autowired
	private AttrValueMapper attrValueMapper;
	@Autowired
	private AssetRecordMapper assetRecordMapper;
	@Autowired
	private LightDataMapper lightMapper;
	
	
	private ReaderInfoSender topicSender = (ReaderInfoSender) ContextUtils.getBean("readerInfoSender");
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<ItAsset> queryList(Page<ItAsset> page, Map<String, Object> params) {
		page.setRecords(itassetMapper.queryList(page,params));
		return page;	
	}
	
	/**
	 * 修改设备信息
	 * @param assetTypeValue
	 */
	public void editAssetInfo(AssetTypeValue assetDe) {
		if(assetDe.getList()!=null&&assetDe.getList().size()>0){
			attrValueMapper.deleteByAssetId(assetDe.getAssetId());
			List<AssetTypeValue> list=assetDe.getList();
			for(AssetTypeValue curr :list){
				curr.setCreateTime(new Date());
				curr.setCreateBy(WebUtil.getCurrentUser());
			}
			attrValueMapper.insertIntoAttrValue(assetDe.getAssetId(),list);
		}
		
		//更新资产表信息
		ItAssetVo vo =assetDe.getValues();
		ItAsset asset = new ItAsset();
		asset.setId(assetDe.getAssetId());
		asset.setAssetName(vo.getAssetName());
		asset.setAssetNo(vo.getAssetNo());
		asset.setBrandId(vo.getBrandId());
		asset.setModelId(vo.getModelId());
		asset.setPrice(vo.getPrice());
		asset.setRemark(vo.getRemark());
		asset.setRfidNo(vo.getRfidNo()!=null?vo.getRfidNo().toUpperCase():"");
		asset.setRfidNo1(vo.getRfidNo1());
		asset.setSerialNo(vo.getSerialNo());
		asset.setIp(vo.getIp());
		asset.setTypeId(vo.getTypeId());
		asset.setUpdateTime(new Date());
		asset.setUpdateBy(WebUtil.getCurrentUser());
		itassetMapper.updateItAssetById(asset);
		
		int uHeight = itassetMapper.getUheight(vo.getModelId());
		if(uHeight==0){
			uHeight =1;
		}
		
		ItAssetExtPosition ext =new ItAssetExtPosition();
		ext.setAssetId(assetDe.getAssetId());
		ext.setAssetPid(vo.getAssetPid());
		ext.setRackId(vo.getRackId());
		ext.setRoomId(vo.getRoomId());
		ext.setStart(vo.getStartU());
		ext.setEnd(vo.getStartU()+uHeight-1);		
		ext.setUpdateTime(new Date());
		ext.setUpdateBy(WebUtil.getCurrentUser());
		itassetExtPositionMapper.updateItAssetExtPosition(ext);
		
		//插入资产扩展表
		 AssetExtMaintenance mainter = new AssetExtMaintenance();
		 mainter.setAssetId(assetDe.getAssetId());
		 mainter.setPrice(vo.getPrice());
		 mainter.setContacts(vo.getContacts());
		 mainter.setContactsPhone(vo.getContactsPhone());
		 mainter.setContractNo(vo.getContractNo());
		 mainter.setSupplier(vo.getSupplier());
		 mainter.setExpirationTime(vo.getExpirationTime());
		 mainter.setBuyTime(vo.getBuyTime());
		 mainter.setHotline(vo.getHotline());
		 mainter.setInvoiceNo(vo.getInvoiceNo());
		 mainter.setUpdateTime(new Date());
		 mainter.setUpdateBy(WebUtil.getCurrentUser());
		 maintenanceMapper.updateAssetExtMaintenance(mainter);
		 
		 //更新资产使用表
		 AssetExtUsing useing = usingMapper.getUsingByAsset(assetDe.getAssetId());
		 if(useing!=null) {
			 useing.setAssetId(assetDe.getAssetId());
			 useing.setUpdateBy(WebUtil.getCurrentUser());
			 useing.setManageBranchId(vo.getManageBranchId());
			 useing.setUseBranchId(vo.getUseBranchId());
			 if(vo.getEndUser()!=null){
				 useing.setEndUser(Long.parseLong(vo.getEndUser()));
			 }
			 useing.setUpdateTime(new Date());			 
			 usingMapper.updateAssetExtUsing(useing);
		 }else {
			 AssetExtUsing use = new AssetExtUsing();
			 use.setId(IdWorker.getId());
			 use.setAssetId(asset.getId());
			 use.setManageBranchId(vo.getManageBranchId());
			 use.setUseBranchId(vo.getUseBranchId());
			 if(!"".equals(vo.getEndUser())&&vo.getEndUser()!=null){
				 use.setEndUser(Long.parseLong(vo.getEndUser()));
			 }
			 use.setCreateBy(WebUtil.getCurrentUser());
			 use.setCreateTime(new Date());
			 usingMapper.insertAssetExtUsing(use);	
		 }
				 
	}
	
	
	public void removeItAsset(Long id){
		itassetMapper.removeItAsset(id);	
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public ItAsset qryById(Long id) {
		return itassetMapper.qryById(id);
	}
	
	/**
	 * 查询所有机柜
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<ItAsset> queryRackList(Long roomId) {
		return itassetMapper.queryRackList(roomId);
	}
	
	/**
	 * 查询机柜总个数
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public int qryRackCount() {
		return itassetMapper.qryRackCount();
	}
	
	/**
	 * 查询U位总个数
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public int qryUcount() {
		return itassetMapper.qryUcount();
	}

	/**
	 * 查询RfidNo是否被占用
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Integer qryByRfidNo(Map<String, Object> map) {
		return itassetMapper.qryByRfidNo(map);
	}
	
	/**
	 * 查询assetNo是否被占用
	 * @param assetNoMap
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Integer qryByAssetNo(Map<String, Object> assetNoMap) {
		return itassetMapper.qryByAssetNo(assetNoMap);
	}
	
	public Boolean createItAsset(AssetExtPositionParam asset) {
		PresetDetail detail = presetDetailMapper.qryDetailById(asset.getPresetDetailId());
		//判断起始U位和结束U位是否被占用
		if(detail==null) return false;
			//插入资产表
			asset.setId(IdWorker.getId());
			asset.setStatus(5);
			asset.setIsDistribute(false);
			asset.setIsBorrow(false);
			asset.setAssetName(detail.getAssetName());
			asset.setRfidNo(asset.getRfidNo()!=null?asset.getRfidNo().toUpperCase():"");
			asset.setAssetNo(detail.getAssetNo());
			asset.setBrandId(detail.getBrandId());
			asset.setTypeId(detail.getTypeId());
			asset.setModelId(detail.getModelId());
			asset.setCreateBy(WebUtil.getCurrentUser());
			asset.setCreateTime(new Date());
			asset.setPrice(detail.getPrice());
			asset.setRemark(detail.getRemark());
			itassetMapper.insertItAsset(asset);		
			
			//更新预置详情单为入库
			PresetDetail pd =new PresetDetail();
			pd.setStatus(2);
			pd.setId(asset.getPresetDetailId());
			pd.setRfidNo(asset.getRfidNo().toUpperCase());
			pd.setSerialNo(asset.getSerialNo());
			presetDetailMapper.updatePresetDetail(pd);
			
			//插入资产扩展表
			ItAssetExtPosition posi= new ItAssetExtPosition();
			posi.setId(IdWorker.getId());
			posi.setAssetId(asset.getId());
			posi.setCreateBy(WebUtil.getCurrentUser());
			posi.setCreateTime(new Date());
			posi.setRoomId(detail.getRoomId());
			itassetExtPositionMapper.insertItAssetExtPosition(posi);
			
			AssetExtUsing extUse =new AssetExtUsing();
			extUse.setId(IdWorker.getId());
			extUse.setAssetId(asset.getId());
			extUse.setCreateBy(WebUtil.getCurrentUser());
			extUse.setCreateTime(new Date());
			usingMapper.insertAssetExtUsing(extUse);			
			
			List<PresetDetail> detailList = presetDetailMapper.queryDetailList(detail.getPresetId());
			 if(detailList!=null&&detailList.size()>0){
				 boolean isAllComplete=true;
				 for(PresetDetail pdetail:detailList){
					 if(pdetail.getStatus()==1){
						 isAllComplete=false;
					 }
				 }
				 Preset p=new Preset();
				 p.setId(detail.getPresetId());
				 p.setStatus(2);
				 if(isAllComplete){
					 p.setStatus(3);
				 }
				 presetMapper.updatePreset(p);
			 }
			 
			 //插入资产扩展表
			 AssetExtMaintenance mainter = new AssetExtMaintenance();
			 mainter.setAssetId(asset.getId());
			 mainter.setId(IdWorker.getId());
			 mainter.setPrice(detail.getPrice());
			 mainter.setContacts(detail.getContacts());
			 mainter.setContactsPhone(detail.getContactsPhone());
			 mainter.setContractNo(detail.getContractNo());
			 mainter.setSupplier(detail.getSupplier());
			 mainter.setExpirationTime(asset.getExpirationTime());
			 mainter.setBuyTime(asset.getBuyTime());
			 mainter.setHotline(asset.getHotline());
			 mainter.setInvoiceNo(asset.getInvoiceNo());
			 mainter.setCreateBy(WebUtil.getCurrentUser());
			 mainter.setCreateTime(new Date());
			 maintenanceMapper.insertAssetExtMaintenance(mainter);
			 //插入资产生命周期表记录
			 AssetRecord re = new AssetRecord();
			 re.setId(IdWorker.getId());
			 re.setAssetId(asset.getId());
			 re.setRfidNo(asset.getRfidNo()!=null?asset.getRfidNo().toUpperCase():"");
			 re.setType(1);
			 re.setCreateBy(WebUtil.getCurrentUser());
			 re.setCreateTime(new Date());
			 assetRecordMapper.create(re);
		     return true;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<ItAssetVo> querAssetListByParam(Page<ItAssetVo> page,Map<String, Object> params) {
		page.setRecords(itassetMapper.querAssetListByParam(page,params));
		return page;
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<ItAssetVo> qryAssetByParamInstock(Page<ItAssetVo> page, Map<String, Object> params) {
		page.setRecords(itassetMapper.qryAssetByParamInstock(page,params));
		return page;
	}
	

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<ItAssetVo> qryItAssetVo(Long applyDetailId) {
		return itassetMapper.qryItAssetVo(applyDetailId);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<ItAssetVo> qryPutOnDetailVo(Long id) {
		return itassetMapper.qryPutOnDetailVo(id);
		
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<ItAssetVo> qryScrapDetailVo(Long id) {
		return itassetMapper.qryScrapDetailVo(id);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<ItAssetVo> queryAssetList(Page<ItAssetVo> page, Map<String, Object> params) {
		page.setRecords(itassetMapper.queryAssetList(page,params));
		return page;	
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public ItAssetVo qryAssetById(Long assetId) {
		return itassetMapper.qryAssetById(assetId);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Boolean existsSerialNo(Map<String, Object> params) {
		int count = itassetMapper.existsSerialNo(params);
		return count>0?true:false;
	}

	/**
	 * 设备总个数
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public int qryAssetCount() {
		return itassetMapper.qryAssetCount();
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<HashMap<String,Object>> qryAssetCountByRoom(Long roomId) {
		return itassetMapper.qryAssetCountByRoom(roomId);
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<HashMap<String,Object>> qryAssetPerGroupByRoom() {
		 List<HashMap<String,Object>> list = itassetMapper.qryAssetPerGroupByRoom();
		 HashMap<String,Object> map =itassetMapper.qryOtherCount();
		 if(map!=null){
			 map.put("name", "其他");
			 map.put("value", map.get("sumCount"));
			 list.add(map);
		 }
		 return list;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<HashMap<String,Object>> qryUPerGroupByRoom() {
		return itassetMapper.qryUPerGroupByRoom();		
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<Map<String, Object>> queryRackFor3D(String roomCode) {
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		try {
			Long roomId = tRoomMapper.qryRoomByCode(roomCode);
			List<Map<String, Object>> rackList = itassetMapper.getRacksByRoomName(roomId);
			List<Map<String, Object>> serverList = itassetMapper.getServersByRoomName(roomId);
			
			if (rackList != null && rackList.size() > 0) {
				for (int i = rackList.size() - 1; i > -1; i--) {
					if (rackList.get(i) == null)
						continue;
					Map<String, Object> temp = new HashMap<String, Object>();
					temp.put("Code", rackList.get(i).get("Code").toString());
					temp.put("Type", rackList.get(i).get("Type"));
					temp.put("Title", rackList.get(i).get("Title"));
					temp.put("BaseModel", rackList.get(i).get("BaseModel"));
					temp.put("OwnerCode", "room-1");
					//
					Map<String, Object> spaceMap = new HashMap<String, Object>();
					spaceMap.put("Rotation", rackList.get(i).get("rotation"));

					Map<String, Object> originMap = new HashMap<String, Object>();
					originMap.put("x", rackList.get(i).get("x_"));
					originMap.put("y", rackList.get(i).get("y_"));
					originMap.put("z", rackList.get(i).get("z_"));
					spaceMap.put("Origin", originMap);
					//
					temp.put("Space", spaceMap);
					resultList.add(temp);
				}
			}
			if (serverList != null && serverList.size() > 0) {
				for (int i = 0; i < serverList.size(); i++) {
					if (serverList.get(i) == null)
						continue;
					// temp.put("BaseModel", "Server/dell/dell_r310");
					if(serverList.get(i).get("OwnerCode")!=null){
						Map<String, Object> temp = new HashMap<String, Object>();
						temp.put("Code", serverList.get(i).get("Code").toString());
						temp.put("Type", serverList.get(i).get("Type"));
						temp.put("Title", serverList.get(i).get("Title"));
						temp.put("BaseModel", serverList.get(i).get("BaseModel"));
						temp.put("OwnerCode", serverList.get(i).get("OwnerCode").toString());
						temp.put("OwnerTitle", serverList.get(i).get("OwnerTitle"));
						Map<String, Object> spaceMap = new HashMap<String, Object>();
						if(!"".equals(serverList.get(i).get("start_"))&&serverList.get(i).get("start_")!=null) {
							spaceMap.put("OwnerIndex", Integer.parseInt(serverList.get(i).get("start_").toString()));
						}else {
							spaceMap.put("OwnerIndex",1);
						}
						
						temp.put("Space", spaceMap);
						resultList.add(temp);
					}				
					
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Map<String, Object> getRackInfo(String rackCode) throws UnsupportedEncodingException {
		Map<String, Object> rackMap = new HashMap<String, Object>();
		Map<String, Object> rackInfo = itassetMapper.getRackInfo(rackCode);
		if (rackInfo != null) {
			if (rackInfo.get("NAME") != null)
					rackMap.put(URLEncoder.encode("机柜名称", "UTF-8"),
							URLEncoder.encode(rackInfo.get("NAME").toString(), "UTF-8"));
			if (rackInfo.get("ASSET_CODE") != null)
				rackMap.put(URLEncoder.encode("资产号", "UTF-8"),
						URLEncoder.encode(rackInfo.get("ASSET_CODE").toString(), "UTF-8"));
			if (rackInfo.get("TYPE") != null)
				rackMap.put(URLEncoder.encode("资产分类", "UTF-8"),
						URLEncoder.encode(rackInfo.get("TYPE").toString(), "UTF-8"));
			if (rackInfo.get("ROOM") != null)
				rackMap.put(URLEncoder.encode("所属机房", "UTF-8"),
						URLEncoder.encode(rackInfo.get("ROOM").toString(), "UTF-8"));
			if (rackInfo.get("uHeight") != null)
				rackMap.put(URLEncoder.encode("U高", "UTF-8"),
						URLEncoder.encode(rackInfo.get("uHeight").toString(), "UTF-8"));
		}
		return rackMap;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Map<String, Object> getServerInfo(String serverCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, Object> assets = itassetMapper.getServerInfo(serverCode);
			if (assets != null) {
				if (assets.get("NAME") != null)
					map.put(URLEncoder.encode("主机名", "UTF-8"),
							URLEncoder.encode(assets.get("NAME").toString(), "UTF-8"));
				if (assets.get("SERIAL_NO") != null)
					map.put(URLEncoder.encode("序列号", "UTF-8"),
							URLEncoder.encode(assets.get("SERIAL_NO").toString(), "UTF-8"));
				if (assets.get("ASSET_CODE") != null)
					map.put(URLEncoder.encode("资产编号", "UTF-8"),
							URLEncoder.encode(assets.get("ASSET_CODE").toString(), "UTF-8"));	
				if (assets.get("rfid_no") != null)
					map.put(URLEncoder.encode("RFID号", "UTF-8"),
							URLEncoder.encode(assets.get("rfid_no").toString(), "UTF-8"));	
				if (assets.get("TYPE_NAME") != null)
					map.put(URLEncoder.encode("设备类型", "UTF-8"),
							URLEncoder.encode(assets.get("TYPE_NAME").toString(), "UTF-8"));
				if (assets.get("BRAND") != null)
					map.put(URLEncoder.encode("品牌", "UTF-8"),
							URLEncoder.encode(assets.get("BRAND").toString(), "UTF-8"));
				if (assets.get("MODEL_NAME") != null)
					map.put(URLEncoder.encode("型号", "UTF-8"),
							URLEncoder.encode(assets.get("MODEL_NAME").toString(), "UTF-8"));	
				if (assets.get("rackName") != null)
					map.put(URLEncoder.encode("所在机柜", "UTF-8"),
							URLEncoder.encode(assets.get("rackName").toString(), "UTF-8"));
				if (assets.get("u_height") != null)
					map.put(URLEncoder.encode("U高", "UTF-8"),
							URLEncoder.encode(assets.get("u_height").toString(), "UTF-8"));
				String u="0";
				if (assets.get("START") != null){
					u =assets.get("START").toString();
				}
				if (assets.get("END") != null){
					u =assets.get("START").toString()+"-"+assets.get("END").toString();
				}
				map.put(URLEncoder.encode("位置信息", "UTF-8"),
							URLEncoder.encode(u+ "U", "UTF-8"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<TRoom> getRackListByUserId() {
		List<TRoom> list = tRoomMapper.getRoomByUser();
		if(list!=null&&list.size()>0){
			for(TRoom t:list){
				List<ItAsset> rackList = itassetMapper.queryRackListByUserId(t.getId()); 
				t.setRackList(rackList);
			}
		}
		return list;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Integer qryAssetByRfidNo(Map<String, Object> map) {
		return itassetMapper.qryAssetByRfidNo(map);
	}

	public void delAsset(List<Long> cmdbIds) {
		for(Long assetId :cmdbIds){
			itassetMapper.removeItAsset(assetId);
			//删除扩展表  和维保表
			itassetExtPositionMapper.removeAsset(assetId);		
			maintenanceMapper.removeAssetMaintenance(assetId);
			//删除预置表
			presetDetailMapper.removePresetDetailByCmdbId(assetId);
		}
	}

	/**
	 * 同步CMDB的U位信息
	 * @param asset
	 */
	public String updateItAsset(ItAssetVo asset) {
		Long assetId = asset.getId();
		String roomName = asset.getRoomName();
		String rackName = asset.getRackName();
		Integer startU =  asset.getStartU();
		Integer endU = asset.getEndU();
		
		TRoom room = tRoomMapper.qryRoomByName(roomName);
		Long rackId = itassetMapper.getRackIdByName(rackName);
		if(rackId!=null){
			ItAsset itasset = new ItAsset();
			itasset.setId(assetId);
			itasset.setSerialNo(asset.getSerialNo());
			itassetMapper.updateItAsset(itasset);
			ItAssetExtPosition extPosition = new ItAssetExtPosition();
			extPosition.setAssetId(assetId);
			extPosition.setRoomId(room.getId());    
			extPosition.setRackId(rackId);
			extPosition.setStart(startU);
			extPosition.setEnd(endU);
			extPosition.setUpdateTime(new Date());
			itassetExtPositionMapper.updateItAssetExtPositionByAssetId(extPosition);
			return null;
		}else{
			return "该机柜:"+rackName+"名称没有在3D系统中找到";
		}
		
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<Map<String, Object>> queryRackFor3DTest() {
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		try {
			List<Map<String, Object>> rackList = itassetMapper.queryFor3DTest();
			List<Map<String, Object>> serverList = itassetMapper.queryRackFor3DTest();
		
			if (rackList != null && rackList.size() > 0) {
				for (int i = rackList.size() - 1; i > -1; i--) {
					if (rackList.get(i) == null)
						continue;
					Map<String, Object> temp = new HashMap<String, Object>();
					temp.put("Code", rackList.get(i).get("Code").toString());
					temp.put("Type", rackList.get(i).get("Type"));
					temp.put("Title", rackList.get(i).get("Title"));
					temp.put("BaseModel", rackList.get(i).get("BaseModel"));
					temp.put("OwnerCode", "room-1");
					//
					Map<String, Object> spaceMap = new HashMap<String, Object>();
					spaceMap.put("Rotation", rackList.get(i).get("rotation"));

					Map<String, Object> originMap = new HashMap<String, Object>();
					originMap.put("x", rackList.get(i).get("x_"));
					originMap.put("y", rackList.get(i).get("y_"));
					originMap.put("z", rackList.get(i).get("z_"));
					spaceMap.put("Origin", originMap);
					//
					temp.put("Space", spaceMap);
					resultList.add(temp);
				}
			}
			
			if (serverList != null && serverList.size() > 0) {
				for (int i = 0; i < serverList.size(); i++) {
					if (serverList.get(i) == null)
						continue;
					// temp.put("BaseModel", "Server/dell/dell_r310");
					if(serverList.get(i).get("start_")!=null){
						Map<String, Object> temp = new HashMap<String, Object>();
						temp.put("Code", (serverList.get(i).get("Code")!=null&&!"".equals(serverList.get(i).get("Code")))?serverList.get(i).get("Code").toString():"");
						temp.put("Type", serverList.get(i).get("Type"));
						temp.put("Title", serverList.get(i).get("Title"));
						temp.put("BaseModel", serverList.get(i).get("BaseModel"));
						temp.put("OwnerCode", serverList.get(i).get("OwnerCode").toString());
						temp.put("OwnerTitle", serverList.get(i).get("OwnerTitle"));
						Map<String, Object> spaceMap = new HashMap<String, Object>();
						spaceMap.put("OwnerIndex", serverList.get(i).get("start_"));
						temp.put("Space", spaceMap);
						resultList.add(temp);
					}
					
					
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	public Boolean onLight(String assetLable) {    
		Map<String,Object> map =itassetMapper.qryAssetLable(assetLable);
		List<OnLightParam> list = new ArrayList<OnLightParam>();
		if(map!=null) {
			if(!"".equals(map.get("rfid_no1"))) {
				System.out.println("222");
    			RfidState data =rfidStateMapper.qryReaderDataByAssetLable(String.valueOf(map.get("rfid_no1")));
    			if(data!=null) {    				
    				String devIp =readerInfoMapper.getDevIp(data.getRackConverCode());
    				System.out.println(devIp+"333");
        			OnLightParam r = new OnLightParam();
        			r.setLabel24g(assetLable);
        			r.setDevAddrCode(data.getRackConverCode());
        			r.setDevIp(devIp);
        			r.setIsLight(1);
        			list.add(r);
        			
        			String rack24g =itassetMapper.getRack24g(String.valueOf(map.get("rfid_no1")));
        			if(rack24g!=null){
        				RfidState dataR =rfidStateMapper.qryReaderDataByAssetLable(rack24g);
            			if(data!=null) {    				
            				String devIpR =readerInfoMapper.getDevIp(data.getRackConverCode());
                			OnLightParam rr = new OnLightParam();
                			rr.setLabel24g(rack24g);
                			rr.setDevAddrCode(dataR.getRackConverCode());
                			rr.setDevIp(devIpR);
                			rr.setIsLight(1);
                			list.add(rr);
        			    }
    			    }
        			
    			}
    		
    		}
	
			if(list!=null&&list.size()>0) {
				CollectBaseReceiverData cbrd= new CollectBaseReceiverData();
				cbrd.setActionCode("collect010");
				cbrd.setAwsPostData(list);
				String json = JSON.toJSONString(cbrd);
				System.out.println(json+"点亮json");
				topicSender.send("serverReader", json);
				//更新数据库表的标签状态为点亮
				for(OnLightParam p:list) {
					ItAsset asset=new ItAsset();
					asset.setRfidNo1(p.getLabel24g());
					asset.setIsLight(1);
					itassetMapper.updateAssetIsLight(asset);
				}
				return true;
			}
			
		}
		return false;
	}

	public Boolean cancleLight(String assetLable) {
		Map<String,Object> map =itassetMapper.qryAssetLable(assetLable);
		List<OnLightParam> list = new ArrayList<OnLightParam>();
		if(map!=null) {
			if(!"".equals(map.get("rfid_no1"))) {
    			RfidState data =rfidStateMapper.qryReaderDataByAssetLable(String.valueOf(map.get("rfid_no1")));
    			if(data!=null) {
	    			String devIp =readerInfoMapper.getDevIp(data.getRackConverCode());
	    			OnLightParam r = new OnLightParam();
	    			r.setLabel24g(assetLable);
	    			r.setDevAddrCode(data.getRackConverCode());
	    			r.setDevIp(devIp);
	    			r.setIsLight(0);
	    			list.add(r);
	    			int count = itassetMapper.qryIsLightCount(String.valueOf(map.get("rfid_no1")));
	    			if(count<2){
	    				String rack24g =itassetMapper.getRack24g(String.valueOf(map.get("rfid_no1")));
		    			if(rack24g!=null){
		    				RfidState dataR =rfidStateMapper.qryReaderDataByAssetLable(rack24g);
		        			if(data!=null) {    				
		        				String devIpR =readerInfoMapper.getDevIp(data.getRackConverCode());
		            			OnLightParam rr = new OnLightParam();
		            			rr.setLabel24g(rack24g);
		            			rr.setDevAddrCode(dataR.getRackConverCode());
		            			rr.setDevIp(devIpR);
		            			rr.setIsLight(0);
		            			list.add(rr);
		    			    }
					    }
	    			}
	    			
    			}
    		}
	
			if(list!=null&&list.size()>0) {
				CollectBaseReceiverData cbrd= new CollectBaseReceiverData();
				cbrd.setActionCode("collect010");
				cbrd.setAwsPostData(list);
				String json = JSON.toJSONString(cbrd);
				System.out.println(json+"取消点亮json");
				topicSender.send("serverReader", json);
				//更新数据库表的标签状态为未
				for(OnLightParam p:list) {
					ItAsset asset=new ItAsset();
					asset.setRfidNo1(p.getLabel24g());
					asset.setIsLight(0);
					itassetMapper.updateAssetIsLight(asset);
				}
				return true;
			}
			
		}
		return false;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Integer qryBy24G(Map<String, Object> map) {
		return itassetMapper.qryBy24G(map);
	}

	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<ItAssetVo> queryAssetListNoPage(Map<String, Object> params) {
		return itassetMapper.queryAssetListNoPage(params);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<AssetExlVo> queryAttrVlaueByTypeIdAndAssetId(Long typeId, Long assetId) {
		List<AssetExlVo> a =itassetMapper.queryAttrVlaueByTypeIdAndAssetId(typeId,assetId);
		return a;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<AssetTypeAttr> queryAttrByTypeId(String typeId) {
		return itassetMapper.queryAttrByTypeId(typeId);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public String queryTypeNameByTypeId(String typeId) {
		return itassetMapper.queryTypeNameByTypeId(typeId);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<String> queryAllAssetNoList() {
		return itassetMapper.queryAllAssetNoList();
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<String> queryAllAssetRFIDList() {
		return itassetMapper.queryAllAssetRFIDList();
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<TRoom> queryRoomList() {
		return itassetMapper.queryRoomList();
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<ItAsset> queryAllRackList() {
		return itassetMapper.queryAllRackList();
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<Department> queryAllDepartmentList() {
		return itassetMapper.queryAllDepartmentList();
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<User> queryAllUserList() {
		return itassetMapper.queryAllUserList();
	}

	public int batchInsertAsset(List<ItAssetVo> interimList) {
		return itassetMapper.batchInsertAsset(interimList);
	}

	public int batchInsertExtPositon(List<ItAssetExtPosition> interimList) {
		return itassetMapper.batchInsertExtPositon(interimList);
	}

	public int batchInsertExtUsing(List<AssetExtUsing> interimList) {
		return itassetMapper.batchInsertExtUsing(interimList);
	}

	public int batchInsertExtMaintenance(List<AssetExtMaintenance> interimList) {
		return itassetMapper.batchInsertExtMaintenance(interimList);
	}

	public int batchInsertAttrValue(List<AssetTypeValue> interimList) {
		return itassetMapper.batchInsertAttrValue(interimList);
	}
	
	public LinkedHashMap<String, Object> queryCount3D(String roomCode) {
		Long roomId = tRoomMapper.qryRoomByCode(roomCode);
		List<Map<String, Object>> rackList = itassetMapper.getRacksByRoomName(roomId);
		LinkedHashMap<String, Object> spaceMap = new LinkedHashMap<String, Object>();
		int rack=0;
		if(rackList!=null&&rackList!=null) {
			rack=rackList.size();
		}
		
		List<Map<String, Object>> alarmList = alarmMapper.getAlarm3d(roomCode);
		int alarm=0;
		if(alarmList!=null&&alarmList!=null) {
			alarm=alarmList.size();
		}
			spaceMap.put("WarnNum", alarm+"");
			spaceMap.put("RoleNum", rack+"");
			spaceMap.put("PowerUsed", 10);
			spaceMap.put("PowerUnused", 5);
			spaceMap.put("SpaceUsed", 105);
			spaceMap.put("SpaceUnused", 124);
		return spaceMap;
	}

	public void exportEXLDate(List<ItAssetVo> assetlList, List<ItAssetExtPosition> extPositonList,
			List<AssetExtUsing> extUsingList, List<AssetExtMaintenance> extMaintenanceList,
			List<AssetTypeValue> attrValueList) {
		if (assetlList!=null&&assetlList.size()>0) {
			List<ItAssetVo> interimList = new ArrayList<ItAssetVo>();
			int j =  (int)Math.ceil(assetlList.size()/(double)50);
			int num =0;
			for (int i = 1; i <= j;i++) {
				if (i*50>=assetlList.size()) {
					for (int k = (i - 1) * 50; k < assetlList.size(); k++) {
						interimList.add(assetlList.get(k));
					}
					num =num+this.batchInsertAsset(interimList);
				}else {
					interimList = assetlList.subList((i - 1) * 50, i * 50);
					num =num+this.batchInsertAsset(interimList);
				}
			}
			if (num!=assetlList.size()) {
				throw new BusinessException("导入数据异常!");
			}
		}
		if (extPositonList!=null&&extPositonList.size()>0) {
			List<ItAssetExtPosition> interimList = new ArrayList<ItAssetExtPosition>();
			int j = (int) Math.ceil(extPositonList.size()/(double)50);
			int num =0;
			for (int i = 1; i <= j;i++) {
				if (i*50>=extPositonList.size()) {
					for (int k = (i - 1) * 50; k < extPositonList.size(); k++) {
						interimList.add(extPositonList.get(k));
					}
					num =num+this.batchInsertExtPositon(interimList);
				}else {
					interimList = extPositonList.subList((i - 1) * 50, i * 50);
					num =num+this.batchInsertExtPositon(interimList);
				}
			}
			if (num!=extPositonList.size()) {
				throw new BusinessException("导入数据异常!");
			}
		}
		if (extUsingList!=null&&extUsingList.size()>0) {
			List<AssetExtUsing> interimList = new ArrayList<AssetExtUsing>();
			int j = (int) Math.ceil(extUsingList.size()/(double)50);
			int num =0;
			for (int i = 1; i <= j;i++) {
				if (i*50>=extUsingList.size()) {
					for (int k = (i - 1) * 50; k < extUsingList.size(); k++) {
						interimList.add(extUsingList.get(k));
					}
					num =num+this.batchInsertExtUsing(interimList);
				}else {
					interimList = extUsingList.subList((i - 1) * 50, i * 50);
					num =num+this.batchInsertExtUsing(interimList);
				}
			}
			if (num!=extUsingList.size()) {
				throw new BusinessException("导入数据异常!");
			}
		}
		if (extMaintenanceList!=null&&extMaintenanceList.size()>0) {
			List<AssetExtMaintenance> interimList = new ArrayList<AssetExtMaintenance>();
			int j = (int) Math.ceil(extMaintenanceList.size()/(double)50);
			int num =0;
			for (int i = 1; i <= j;i++) {
				if (i*50>=extMaintenanceList.size()) {
					for (int k = (i - 1) * 50; k < extMaintenanceList.size(); k++) {
						interimList.add(extMaintenanceList.get(k));
					}
					num =num+this.batchInsertExtMaintenance(interimList);
				}else {
					interimList = extMaintenanceList.subList((i - 1) * 50, i * 50);
					num =num+this.batchInsertExtMaintenance(interimList);
				}
			}
			if (num!=extMaintenanceList.size()) {
				throw new BusinessException("导入数据异常!");
			}
		}
		if (attrValueList!=null&&attrValueList.size()>0) {
			List<AssetTypeValue> interimList = new ArrayList<AssetTypeValue>();
			int j = (int) Math.ceil(attrValueList.size()/(double)50);
			int num =0;
			for (int i = 1; i <= j;i++) {
				if (i*50>=attrValueList.size()) {
					for (int k = (i - 1) * 50; k < attrValueList.size(); k++) {
						interimList.add(attrValueList.get(k));
					}
					num =num+this.batchInsertAttrValue(interimList);
				}else {
					interimList = attrValueList.subList((i - 1) * 50, i * 50);
					num =num+this.batchInsertAttrValue(interimList);
				}
			}
			if (num!=attrValueList.size()) {
				throw new BusinessException("导入数据异常!");
			}
		}
		
	}

	public ItAssetVo qryAssetDetailById(Long assetId) {
		return itassetMapper.qryAssetDetailById(assetId);
	}

	public List<RoomTreeNodeVo> qryRackTree(Long roomId) {
		List<RoomTreeNodeVo> voList = tRoomMapper.qryRackTree(roomId);
		if(voList!=null&&voList.size()>0){
			for(RoomTreeNodeVo vo:voList){
				List<RoomTreeNodeVo> rackList =tRoomMapper.queryRackList(vo.getId());
				vo.setRackList(rackList);
			}
			
		}
		return voList;
	}
	
	/**
	 * 京东点亮
	 * @param param
	 * @param timestemp 
	 * @return
	 */
	public void onLightJd(LightAssetVo param, long timestemp) {    
		String devAddrCode=param.getRackConverCode().toUpperCase();	
		String json ="{\"actioncode\": \"reader005\",\"awsPostdata\":{\"devAddrList\": [{\"devAddrCode\":\""+devAddrCode+"\",\"lightCommandList\": [{\"loopCount\": 255,\"offTime\": 20,\"onTime\": 10,\"u\": "+param.getStartU()+",\"color\":5,\"luminance\":7}]}]},\"timeStamp\": "+timestemp+"}";
		LightU lightU =new LightU();
		lightU.setId(IdWorker.getId());
		lightU.setTimeStamp(timestemp);
		lightU.setLightStatus(false);
		lightU.setCount(1);
		lightU.setU(param.getStartU());
		lightU.setAssetId(param.getAssetId());
		lightU.setDataJson(json);
		lightU.setRackConverCode(devAddrCode);
		lightU.setStatus(true);
		lightU.setCreateTime(new Date());
		lightMapper.insertLightU(lightU);
		System.out.println(json+"手动点亮json");
		topicSender.send("DAIO", json);
	}

	/**
	 * 京东取消点亮
	 * @param param
	 * @return
	 */
	public void cancleLightJd(LightAssetVo param, long timestemp) {
		String devAddrCode=param.getRackConverCode().toUpperCase();	
		String json ="{\"actioncode\": \"reader005\",\"awsPostdata\": {\"devAddrList\": [{\"devAddrCode\":\""+devAddrCode+"\",\"lightCommandList\": [{\"loopCount\": 1,\"offTime\": 20,\"onTime\": 10,\"u\": "+param.getStartU()+",\"color\":0,\"luminance\":0}]}]},\"timeStamp\": "+timestemp+"}";
		LightU lightU =new LightU();
		lightU.setId(IdWorker.getId());
		lightU.setTimeStamp(timestemp);
		lightU.setLightStatus(false);
		lightU.setCount(1);
		lightU.setU(param.getStartU());
		lightU.setAssetId(param.getAssetId());
		lightU.setDataJson(json);
		lightU.setRackConverCode(devAddrCode);
		lightU.setStatus(false);
		lightU.setCreateTime(new Date());
		lightMapper.insertLightU(lightU);
		System.out.println(json+"手动取消点亮json");
		topicSender.send("DAIO", json);
//		LightListener sendListener=new LightListener();
//		sendListener.setTimestemp(timestemp);
//		Thread thread = new Thread(sendListener); 
//		thread.start();

	}


	
	

}
